package app.TouTiao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import qiurank.Config;
import qiurank.PlanInterface;
import qiurank.UrlObject;

/**
 * Created by Administrator on 2016/1/14.
 */
public class Filter implements PlanInterface{
    @Override
    public UrlObject doPlanGetNoPaUrl(List<UrlObject> list) {
        //取出待爬取url的策略
        int len=list.size();
        Random random=new Random();
        int key=random.nextInt(len);
        return list.get(key);
    }

    @Override
    public boolean doPlanAddUrl(String url) {
        if(app.TouTiao.Config.TYPE_QUPAURL==2) {
            for (String nopaurl : app.TouTiao.Config.NOQUPAURL) {
                if (url.contains(nopaurl)) {
                    return false;
                }
            }
            return true;
        }else if(app.TouTiao.Config.TYPE_QUPAURL==1){
            for (String nopaurl : app.TouTiao.Config.MUSTQUPAURL) {
                if (url.contains(nopaurl)) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    /**
     * 过滤正在爬取的url规则，不去抓取页面页面内容的，只抓取页面连接地址的
     * @param url  正要爬取的url
     * @return    满足规则返回false，不满足规则返回true
     */
    public static boolean doPlanPaingUrl(String url){
        for (String pat : app.TouTiao.Config.NOQUGETCONTENT) {
            Pattern pattern=Pattern.compile(pat);
            Matcher matcher=pattern.matcher(url);
            if(matcher.find()){
                return false;
            }
        }
        return true;
    }
    /**
     * 文章内容是否包含配置的关键字，包含返回true 否则返回false
     * @param content  文章内容
     * @return   包含关键字返回true 否则返回false
     */
    public static boolean doPlanFilterKeyWord(String content){
        for (String keyword : app.TouTiao.Config.FILTER_KEYWORD) {
            Pattern pattern=Pattern.compile(keyword.toLowerCase());
            Matcher matcher=pattern.matcher(content.toLowerCase());
            //Log.console(matcher.find());
            if(matcher.find()){
                //Log.console(matcher.group()+",keyword:"+keyword.toLowerCase());
                return true;
            }
        }
        return false;
    }
    /**
     * 过滤文章函数
     * @param articleObject 文章对象
     * @return  满足条件返回true，否则返回false
     */
    public static boolean doPlanFilterArticle(ArticleObject articleObject){

        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, app.TouTiao.Config.FILTER_CREATE_TIME);
            long now = calendar.getTime().getTime();
            if (articleObject.create_time >= now&&articleObject.commentnums>=app.TouTiao.Config.FILTER_COMMENT_NUMS) {
                return true;
            }

        } catch (Exception e) {

        }

        return false;
    }

}
